//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;

namespace Eas.WebCrawler.PlugIns.RequestComparers
{
    /// <summary>Prioritizes requests based on whether or not the current request's host is the same as the host of the current requests's parent.</summary>
    /// <remarks>The intent here is to be able to say 'go broad' or 'go deep'.  In other words, do you choose to prioritize links that stay on the same host, or do you prioritize links that go to a different host.
    /// Priority ties are handled by an inner <see cref="BaseComparer"/>.</remarks>
    public class StayOnHostComparer : BaseRequestDesirabilityComparer
    {
        private bool _StayOnHost;

        /// <summary>Whether to prioritize requests that stay on the same host as their parent above(<code>true</code>) or below (<code>false</code>) other requests.</summary>
        public bool StayOnHost
        {
            get { return _StayOnHost; }
        }

        /// <summary>Constructs a <see cref="StayOnHostComparer"/> from a value determining whether requests to the same host are to be prioritized and an inner <see cref="BaseComparer"/>.</summary>
        /// <param name="stayOnHost">Whether or not to set requests to the same host to be high or low priority.</param>
        /// <param name="innerComparer">An inner <see cref="BaseComparer"/> used to break ties.</param>
        public StayOnHostComparer(bool stayOnHost, BaseComparer innerComparer) : base(innerComparer) { _StayOnHost = stayOnHost; }

        /// <summary>Returns whether or not to prioritize the request based on whether or not the request tries to access a different host than the parent request.</summary>
        /// <param name="request">The request to check.</param>
        /// <returns><code>true</code> if the request is being made to a high priority host, or <code>false</code> otherwise.</returns>
        public override bool IsPreferred(Eas.WebCrawler.Interfaces.Request request)
        {
            if (request.Parent == null)
                return true;

            if (_StayOnHost)
                return String.Equals(request.Uri.Host, request.Parent.Uri.Host, StringComparison.OrdinalIgnoreCase);
            else
                return !String.Equals(request.Uri.Host, request.Parent.Uri.Host, StringComparison.OrdinalIgnoreCase);
        }
    }
}
